package org.example.socketdemos.filecopy;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * ByteBuffer直接分配内存
 */
@Slf4j
public class FileChannelSocket {
    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();

            log.info("连接8080端口");
            socketChannel.connect(new InetSocketAddress(8080));
            log.info("连接成功");


            RandomAccessFile fous = new RandomAccessFile("d:/py3.8.yaml", "rw");

            FileChannel fileChannel = fous.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            int length = -1;
            while ((length = fileChannel.read(buffer)) != -1) {
                socketChannel.write(buffer);
            }

            // 关闭输出流并写一个结束标记
            socketChannel.shutdownOutput();

            buffer.flip();
            while ((length = socketChannel.read(buffer)) != -1) {
                // 应该输出读到的字节数
                log.info(buffer.toString());
            }

            Thread.sleep(Integer.MAX_VALUE);

        } catch (IOException|InterruptedException e) {
            log.error(e.getMessage());
        }
    }
}
